package gazzera.node.core.plugins.download;

import gazzera.node.core.*;
import gazzera.utils.*;

import java.io.*;
import java.util.*;


public class Downloads implements Iterable<Download>
{
	private List<Download> downloads = new ArrayList<Download>();
	private Config config;
	
	public Downloads(Config config)
	{
		this.config = config;
	}


    private File getFile(Config c)
	{
		return new File(c.getMainFolder(), "downloads");
	}
	
    
    @Override
	public Iterator<Download> iterator()
	{
		return downloads.iterator();
	}
	public void save() throws IOException
	{
		File f = getFile(config);
		DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
		try
		{
			dos.writeInt(downloads.size());
			for (Download d : downloads)
			{
				dos.writeUTF(d.getFile().getAbsolutePath());
			}
		}
		finally
		{
			dos.close();
		}
		
	}
    public void remove(Download d) throws IOException
    {
	downloads.remove(d);
    	save();
    }
    
 
    public void add(Download d) throws IOException
    {
		
	downloads.add(d);
	save();
    }
  
    
	//SuppressWarnings("unchecked")
	public void load() throws IOException
	{
		File f = getFile(config);
		if(f.exists())
		{
			DataInputStream dos = new DataInputStream(new FileInputStream(f));
			try
			{
				int x = dos.readInt();
				for (int i = 0; i < x; i++)
				{
					String fi = dos.readUTF();
					Download d = new Download();
					d.load(new File(fi));
					
					downloads.add(d);
				}
			}
			finally
			{
				dos.close();
			}
		}
		else
		{
		    downloads = new ArrayList<Download>();
			save();
		}
		
		int max = 0;
		for (Download d : downloads) {
			if (d.id > max) {
				max = d.id;
			}
		}
		Download.nextId.set(max+1);
		
	}
	
	public boolean isDownloading(FileID fileId)
	{
	    for (Download d : downloads)
	    {
		if(d.fileID.equals(fileId)) return true;
	    }
	    return false;
	}
	
	public Download get(FileID fileId)
	{
	    for (Download d : downloads)
	    {
	    	if(d.fileID.equals(fileId)) return d;
	    }
	    return null;
	}


	public Download getById(int id) {
		for (Download d : downloads)
	    {
	    	if(d.id == id) return d;
	    }
	    return null;
	}

}
